package org.tuproj.drujbapizza;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.DefaultHttpClient;
import org.tuproj.durjbapizza.client.HttpClientSingleton;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * Activity that is used for loading JSON data from Server.
 * 
 * @author Radoslav Penev
 */

public class LoadingActivity extends Activity {
	private EditText etUsername;
	private EditText etPassword;
	private Button loginButton;
	private Button btnRegister;

	/**
	 * Calls async object and start menu acitvity
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_loading);
		etUsername = (EditText) findViewById(R.id.etUsername);
		etPassword = (EditText) findViewById(R.id.etPassword);
		loginButton = (Button) findViewById(R.id.btnLogin);
		btnRegister = (Button) findViewById(R.id.btnRegister);
		etUsername.setVisibility(View.VISIBLE);
		etPassword.setVisibility(View.VISIBLE);
		loginButton.setVisibility(View.VISIBLE);
		btnRegister.setVisibility(View.VISIBLE);

	}

	/**
	 * Login to Restful service if needed and parsing data;
	 * 
	 */
	private void loadDataAndLoginIfNeeded() {
		final ProgressDialog dialog = ProgressDialog.show(this,
				"Loading data from server", "Please wait...", true);
		dialog.show();
		Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				LoginTask task = new LoginTask();
				task.execute(new String[] {
						"http://10.0.2.2:8080/pizza-rest/rest/user/hello",
						"http://10.0.2.2:8080/pizza-rest/rest/pizza/list" });
				dialog.dismiss();
			}
		}, 8000);

	}

	/**
	 * Async task that creates HTTP queries to Server.
	 */
	private class LoginTask extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			String loginStatus = "";
			CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
			credentialsProvider.setCredentials(new AuthScope(
					AuthScope.ANY_HOST, AuthScope.ANY_PORT),
					new UsernamePasswordCredentials(etUsername.getText()
							.toString(), etPassword.getText().toString()));
			DefaultHttpClient client = HttpClientSingleton.getInstance();
			client.setCredentialsProvider(credentialsProvider);

			HttpGet getQuery = new HttpGet(params[0]);
			getQuery.addHeader("accept", "application/json");
			try {
				HttpResponse response = client.execute(getQuery);
				int responseCode = Integer.valueOf(response.getStatusLine()
						.getStatusCode());
				Log.i("Server response by logging",
						Integer.valueOf(responseCode).toString());
				if (responseCode == 401) {
					loginStatus = "FAIL";

				} else if (responseCode == 200) {

					getQuery = new HttpGet(params[1]);
					response = client.execute(getQuery);
					StringBuilder responseBuilder = new StringBuilder();
					InputStream content = response.getEntity().getContent();
					BufferedReader buffer = new BufferedReader(
							new InputStreamReader(content));
					String line = "";
					while ((line = buffer.readLine()) != null) {
						responseBuilder.append(line);
					}
					loginStatus = "OK" + responseBuilder.toString();
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			return loginStatus;
		}

		@Override
		protected void onPostExecute(String result) {
			if ("FAIL".equals(result)) {
				Toast.makeText(getApplicationContext(), result,
						Toast.LENGTH_LONG).show();
			} else if (result.startsWith("OK")) {
				
				Intent i = new Intent(LoadingActivity.this,
						PizzaMenuActivity.class);
				String string = result.substring(2,result.length());
				Log.i("Result", string);
				i.putExtra("JSON_STRING", string);
				startActivity(i);
			}
		}

	}

	/**
	 * Options menu
	 * 
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_loading, menu);
		return true;
	}

	/**
	 * Login Button click event
	 * 
	 */
	public void login(View v) {
		loadDataAndLoginIfNeeded();
	}

	/**
	 * Register button click event
	 * 
	 */
	public void registerNewUser(View v) {
		startActivity(new Intent(this, RegisterActivity.class));
	}

}
